import { fetchList, expt, exportExcel } from '@/services/pay/PayCharge';
import { message } from 'antd';

export default {
  namespace: 'PPaymentCharge',

  state: {
    dataTable: {
      total: 0,
      list: [],
    },
  },

  effects: {
    * fetchList({ payload }, { call, put }) {
      const response = yield call(fetchList, payload);
      if (response.code === 0) {
        let dataTable = response.data;
        dataTable.list = dataTable.list.map(d => {
          d.mchName = d.mchInfo?.name;
          d.payChannelName = d.payChannel?.name;
          return d;
        });
        yield put({
          type: 'chgDataTable',
          payload: dataTable,
        });
      }
    },

    * expt({ payload, callback }, { call }) {
      const response = yield call(expt, payload);
      if (response.code === 0) {
        message.success('导出成功').then();
        window.location.href = response.data.url;
        callback && callback();
      }
    },

    * exportExcel({ payload, callback }, { call }) {
      const response = yield call(exportExcel, payload);
      const link = document.createElement('a');
      let blob = new Blob([response], { type: 'application/vnd.ms-excel;charset=utf-8' });
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      link.download = 'mch_charge_' + new Date().getTime() + '.xlsx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
  },

  reducers: {
    chgDataTable(state, action) {
      return {
        ...state,
        dataTable: action.payload,
      };
    },
    saveFile({ payload: { blob, fileName } }, { call }) {
      console.log(blob);
      let link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName;
      //此写法兼容可火狐浏览器
      document.body.appendChild(link);
      let evt = document.createEvent('MouseEvents');
      evt.initEvent('click', false, false);
      link.dispatchEvent(evt);
      document.body.removeChild(link);
    },
  },
};
